#include <unistd.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <iostream>

class TCPserver
{
public:
  TCPserver(const uint16_t port) : _port(port)
  {}
  ~TCPserver() {}
  void init()
  {
    _sock = socket(AF_INET, SOCK_STREAM, 0);
    if(_sock < 0)
    {
      std::cout << "create sock failed\n";
      exit(-1);
    }

    struct sockaddr_in addr;
    addr.sin_addr.s_addr = INADDR_ANY;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(_port);
    if(bind(_sock, (struct sockaddr*)&addr, sizeof addr) < 0)
    {
      std::cout << "bind failed\n";
      exit(-1);
    }
  }

  void run()
  {
    listen(_sock, 5);
    while(1)
    {
      struct sockaddr_in client;
      socklen_t sz = sizeof(client);
      int cli = accept(_sock, (struct sockaddr*)&client, &sz);
      std::cout << "connnect success\n";
      while(1)
      {
        char buffer[1024];
        socklen_t sz = sizeof(buffer);
        int ret = recv(cli, buffer, sizeof(buffer) - 1, 0);
        buffer[ret] = '\0';
        std::cout << "ret = " << ret << "recv : " << buffer << std::endl;
        // send(_sock, buffer, sizeof(buffer), 0);
      }
    }   
  }
private:
  uint16_t _port;
  int _sock;
};
